package com.itheima.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.itheima.core.BaseServlet;
import com.itheima.domain.system.Dept;

import com.itheima.service.system.DeptService;
import com.itheima.service.system.impl.DeptServiceImpl;
import com.itheima.utils.BeanUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/system/dept/*")
public class DeptServlet extends BaseServlet {
    private DeptService deptService = new DeptServiceImpl();

    /**
     * 跳转到列表页面
     */
    public String list(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");

        if (StringUtil.isEmpty(pageNum)) {
            pageNum = "1";
        }
        if (StringUtil.isEmpty(pageSize)) {
            pageSize = "5";
        }

        PageInfo<Dept> deptPageInfo = deptService.queryPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));

        request.setAttribute("page", deptPageInfo);
        return "/WEB-INF/pages/system/dept/list.jsp";
    }



    public String toAdd(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Dept> all = deptService.findAll();
        request.setAttribute("deptList",all);
        return "/WEB-INF/pages/system/dept/add.jsp";
    }

    public String save(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Dept dept = BeanUtil.fillBean(request, Dept.class, "yyyy-MM-dd");
        deptService.save(dept);
        return "/system/dept/list";
    }

    public String delete(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String[] ids = request.getParameterValues("id");
        for (String id : ids) {
            deptService.deleteById(id);
        }
        return "/system/dept/list";
    }

    public String toEdit(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String id = request.getParameter("id");
        Dept byId = deptService.findById(id);
        request.setAttribute("dept",byId);
        List<Dept> all = deptService.findAll();
        request.setAttribute("deptList",all);
        return "/WEB-INF/pages/system/dept/update.jsp";
    }

    public String edit(HttpServletRequest request, HttpServletResponse response)throws Exception{
        /*1.获取表单数据*/
        Dept dept = BeanUtil.fillBean(request, Dept.class, "yyyy-MM-dd");

        /*2.调用se-08rvice*/
        deptService.update(dept);

        /*3.页面跳转*/
        return "/system/dept/list";
    }
}